package org.spider.spiderweb.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.utilDomain.SpiderNode;
import org.spider.api.utils.flow.SpiderFlowUtils;
import org.spider.core.Spider;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * 当前的WebSocket只支持同时只有一个窗口来测试，因为context只有一个<br>
 * 但是可以扩展，那样前端的操作逻辑会发生变化 <br>
 * <br>
 * 可以添加调试器debug功能，原理是线程wait
 */
@Component
@ServerEndpoint("/ws")
public class EditorWebSocketServer {
    private WebSocketContext context;
    //每次新建一个WebSocket都会新建一个实例，但是Spider只需要一个，因此使用方法注入的方式
    public static Spider spider;
    private static Logger log = LoggerFactory.getLogger(EditorWebSocketServer.class);

    @OnMessage
    public void onMessage(String message, Session session) {

        JSONObject event = JSON.parseObject(message);
        String eventType = event.getString("eventType");
        if ("test".equalsIgnoreCase(eventType)) {
            new Thread(() -> {
                String json = event.getString("message");
                if (StringUtils.isNotEmpty(json)) {
                    SpiderNode root = SpiderFlowUtils.loadJsonFromString(json);
                    spider.runTest(root, context);
                    context.write(WebSocketEvent.log("爬虫测试完成"));
                } else {
                    context.write(WebSocketEvent.log("流程图不能为空"));
                }
            }).start();
        } else if ("stop".equalsIgnoreCase(eventType)) {
            
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        log.info("链接成功");
        context = new WebSocketContext(session);
        context.write(WebSocketEvent.log("成功连接websocket"));
    }

    private void write(Session session) {

    }

    @OnClose
    public void onClose() {
        log.info("websocket关闭");
        context.write(WebSocketEvent.log("关闭连接"));
    }
}